package com.ochnas.volunteersignup.service;

import java.util.List;

import org.springframework.orm.jpa.support.JpaDaoSupport;

import com.ochnas.volunteersignup.domain.Event;
import com.ochnas.volunteersignup.domain.Position;
import com.ochnas.volunteersignup.domain.Time;
import com.ochnas.volunteersignup.domain.TimeSlot;

public class EventServiceImpl extends JpaDaoSupport implements EventService {

	@Override
	public Event createEvent(Event e) {
		getJpaTemplate().persist(e);
		return e;
	}

	@Override
	public Position createPositionForEvent(Event e, String name,
			String description, int requiredNumberOfVolunteers) {
		Position p = new Position(name, description, requiredNumberOfVolunteers);
		getJpaTemplate().persist(p);
		
			e.addPosition(name, description, requiredNumberOfVolunteers);
	
//		e = getJpaTemplate().merge(e);
		getJpaTemplate().persist(e);
//		
//		Position[] pArray = e.getPositions().toArray(new Position[0]);
//		for (Position pos: pArray) {
//			System.out.println("Event["+e.getId()+"].contains position id=" + pos.getId());
//		}
//		
//		List<Position> positions = getJpaTemplate().find("from Position");
//		for (Position pos: positions) {
//			System.out.println("TABLE Position contains position id=" + pos.getId());
//		}
//		
//		System.out.println(">>>> RETURNING POSITION:" + p);
		return p;
	}

	@Override
	public TimeSlot createTimeSlotForPosition(Position p, Time startTime,
			Time endTime, int quantityOfVolunteers) {
		TimeSlot ts = p.addTimeSlot(startTime, endTime, quantityOfVolunteers);
		p = getJpaTemplate().merge(p);
		getJpaTemplate().persist(p);
		
		TimeSlot[] tsArray = p.getTimeSlots().toArray(new TimeSlot[0]);
		for (TimeSlot pos: tsArray) {
			System.out.println("Position["+p.getId()+"].contains time slot id=" + pos.getId());
		}
		
		List<TimeSlot> positions = getJpaTemplate().find("from TimeSlot");
		for (TimeSlot pos: positions) {
			System.out.println("TABLE TimeSlot contains time slot id=" + pos.getId());
		}
		
		System.out.println(">>>> RETURNING TIME SLOT:" + ts);
		
		return ts;
	}

	@Override
	public void deleteEvent(Event e) {
		getJpaTemplate().remove(e);
	}

	@Override
	public void deletePositionOfEvent(Position p) {
		getJpaTemplate().remove(p);
	}

	@Override
	public void deleteTimeSlotOfPosition(TimeSlot ts) {
		getJpaTemplate().remove(ts);
	}

	@Override
	public void updateEvent(Event e) {
		e = getJpaTemplate().merge(e);
		getJpaTemplate().persist(e);
	}

	@Override
	public void updatePositionOfEvent(Position p) {
		p = getJpaTemplate().merge(p);
		getJpaTemplate().persist(p);
	}

	@Override
	public void updateTimeSlotOfPosition(TimeSlot ts) {
		ts = getJpaTemplate().merge(ts);
		getJpaTemplate().merge(ts);
	}

}
